package com.lh.biz.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.lh.biz.ICartBiz;
import com.lh.biz.dto.in.cart.AddItemInDto;
import com.lh.biz.dto.out.cart.AddItemOutDto;
import com.lh.dao.ICartDao;
import com.lh.dao.IProductDao;
import com.lh.entity.Cart;
import com.lh.entity.Product;
import com.lh.entity.User;
import com.lh.util.SessionUtil;

/**
 * @author liuhui
 * @version 1.0
 * @date 2013-5-1 下午4:55:11
 */
@Service
public class CartBizImpl implements ICartBiz {
	private Logger logger = Logger.getLogger(getClass());
	@Resource
	private ICartDao cartDao;
	@Resource
	private IProductDao productDao;
	@Override
	public AddItemOutDto addItem(AddItemInDto inDto) {
		AddItemOutDto out = new AddItemOutDto();
		Product p = productDao.selectById(inDto.getProductId());
		if(p == null ){
			logger.warn("product not found ,id="+inDto.getProductId());
			out.setSuccess(false);
			out.setMessage("商品不存在");
			return out;
		}
		Cart userCart = null ;//原有购物车
		Cart cart = null;//现有购物车
		Cart currentCart = null;//当前使用的购物车
		User user = SessionUtil.getUser();
		if(inDto.getCartId() != null){
			cart = cartDao.selectById(inDto.getCartId());
		}
		if(user != null ){
			userCart = cartDao.selectByUserId(user.getId());
		}
		
		//原来没有购物车，现在也没有购物车
		if(userCart  == null  && cart == null ){
			currentCart = new Cart();
			currentCart.setCreateTime(new Date());
			cartDao.insert(currentCart);
		}else
		//原来没有购物车，现在有购物车
		if(userCart == null && cart != null  ){
			currentCart = cart ;
		}else
		//原来有购物车，现在有购物车
		if(userCart != null && cart != null ){
			if(cart.getUser() != null && !user.getId().equals(cart.getUser().getId())){
				logger.warn("cartId been tampered ,id="+cart.getId());
				//cartId被篡改
				cart = null ;
			}else if(!userCart.getId().equals(cart.getId())) {
				userCart.merge(cart);
			}
			currentCart = userCart;
		}
		//原来有购物车，现在没有购物车
		if(userCart != null && cart == null ){
			currentCart = userCart;
		}
		
		currentCart.setUser(user);
		currentCart.addItem(p	, inDto.getQuantity() , true);
		cartDao.update(currentCart);
		out.setTotalAmount(currentCart.getTotalAmount());
		out.setTotalQuantity(currentCart.getTotalQuantity());
		out.setCartId(currentCart.getId());
		return out;
		
		
		
	}

}
